/*
 * Copyright (c) 2009 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package com.sun.spot.wot;

import com.sun.spot.ipv6.io.j2me.udp.UDPConnection;
import com.sun.spot.ipv6.io.j2me.udp.UDPDatagram;
import java.io.IOException;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.DatagramConnection;
import com.sun.spot.wot.http.EncodingException;
import com.sun.spot.wot.http.HttpRequest;
import com.sun.spot.wot.http.HttpResponse;

/**
 *
 * @author vgupta
 */
public class UDP6Handler extends Thread {
    DatagramConnection conn = null;
    NanoAppServer nas = null;
    int maxlen = 0;
    int port = 0;

    public UDP6Handler(int port, NanoAppServer nas) throws IOException {
        this.nas = nas;
        this.port = port;

        conn = (UDPConnection) Connector.open("udp://:" + port);
        maxlen = conn.getMaximumLength();
    }

    public void run() {
        UDPDatagram dg = null;
        boolean done = false;
        byte[] reqBytes = null;
        byte[] resBytes = null;
        HttpRequest req = null;
        HttpResponse res = null;
        Date d = new Date();

        System.out.println(d.toString() + ": Starting UDP6 handler on port " +
                port + "...");
        while (!done) {
            try {
                req = null;
                res = new HttpResponse();
                dg = (UDPDatagram) conn.newDatagram(maxlen);
                dg.reset();
                try {
                    conn.receive(dg);
                    d.setTime(System.currentTimeMillis());
//                    srcAddr = dg.getSrcAddress();
//                    srcPort = dg.getSrcPort();
                    reqBytes = dg.getData();
                    req = HttpRequest.parse(reqBytes, 0, reqBytes.length);
                    System.out.println(d.toString() + ": Received " +
                            req.getMethod() + " " + req.getPathInfo() +
                            ((req.getQueryString() == null) ?
                                "":
                                "?"+req.getQueryString()) + " over UDP from "
                            + dg.getAddress() + ", port " + dg.getSrcPort());
                } catch (Exception ex) {
                    // If there is a problem reading the request, return BAD_INPUT
                    d.setTime(System.currentTimeMillis());
                    System.err.println(d.toString() +
                            ": Caught " + ex + " in UDP6Handler");
                    ex.printStackTrace();
                    req = null;
                    res.setStatus(HttpResponse.SC_BAD_REQUEST);
                }

                if (req != null) {
                    res = nas.getResponse(req);
                }

                resBytes = new byte[maxlen];
                int wlen = res.toByteArray((req == null) ? false :
                    req.isCompressed(), resBytes, 0);
                UDPDatagram ndg = (UDPDatagram) conn.newDatagram(maxlen);
                ndg.reset();
                
                //ndg.setDstAddress(dg.getSrcAddress());
                //ndg.setDstPort(dg.getSrcPort());
                ndg.setAddress(dg); // Sets both address and port
                ndg.write(resBytes, 0, wlen);
                d.setTime(System.currentTimeMillis());
                System.out.println(d.toString() + ": Sent code " + 
                        res.getStatus() + " over UDP to " + dg.getAddress());
                conn.send(ndg);
            } catch (EncodingException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
